/*
  $Id: loading.js 178 2008-06-05 13:48:28Z altblue $

  Loading: AJAX Activity Indicator

  (c) 2003-2007 Marius Feraru <altblue@n0i.net>

  This module is free software; you can redistribute it
  and/or modify it under the same terms as Perl itself.
*/

var Loading = {

  element: false,

  init: function (msg) {
    if (this.element) return false;
    this.element = $T('div', document.body, {id: 'loading'});
    this.element.hide();
    this.title = $T('div', this.element, {className:'loading-title'}).update('Loading…');
    this.msg   = $T('div', this.element, {className:'loading-message'}).update(msg || '');
    return this;
  },

  show: function () {
    this.init();
    if (this.element.visible()) return false;
    if (window.Effect)
      new Effect.Appear(this.element, {duration: 0.2, queue: {position: 'end', scope: 'loading'}});
    else
      this.element.show();
    return this;
  },

  hide: function () {
    this.init();
    if (!this.element.visible()) return false;
    if (window.Effect)
      new Effect.Fade(this.element, {duration: 0.2, queue: {position: 'end', scope: 'loading'}});
    else
      this.element.hide();
    return this;
  },

  type: function (name) {
    this.init();
    var was_visible = this.element.visible();
    if (was_visible) this.element.hide();
    this.element.className = name;
    if (was_visible) this.element.show();
    return this;
  },

  message: function (msg, title) {
    this.init();
    this.title.innerHTML = title;
    this.msg.innerHTML   = msg;
    return this;
  },

  reset: function (msg, title) {
    return this.message(msg || 'Please wait.', title || 'Loading…');
  },

  error: function (msg, title) {
    this.message(msg || 'error!', title || 'Error');
    this.element.show();
    if (window.Effect)
      new Effect.Shake(this.element, {duration: 0.2, queue: {position: 'end', scope: 'loading'}});
    setTimeout(function() { this.hide(); this.reset(); }.bind(this), 5000);
    return this;
  }

};

if (window.Ajax && window.Ajax.Responders)
  Ajax.Responders.register({
    onCreate:   function() { Loading.show() },
    onFailure:  function() { Loading.error() },
    onException: function() { Loading.error() },
    onComplete: function() { Ajax.activeRequestCount || Loading.hide() }
  });
